// pages/mine/editHealthInfo/editHealthInfo.js
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    weight: "",
    height: "",
    type: "",
    index: "",
    order: "",
    heightOp: [],
    weightOp: []
  },
  bindPickerChange(e) {
    var key = e.target.dataset.key;
    if (key == "weight") {
      this.setData({
        [key]: this.data.weightOp[e.detail.value]
      })
    } else {
      this.setData({
        [key]: this.data.heightOp[e.detail.value]
      })
    }

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let heightOp = [],
      weightOp = [];
    for (let i = 0; i < 250; i++) {
      heightOp.push(i + 1);
    }
    for (let i = 0; i < 200; i++) {
      weightOp.push(i + 1);
    }
    let index;
    if (options.height) index = options.height * 1 - 1;
    if (options.weight) index = options.weight * 1 - 1;
    if (!index) {
      index = options.type == 1 ? 169 : 59;
    }
    this.setData({
      weight: options.weight,
      height: options.height,
      type: options.type,
      heightOp: heightOp,
      weightOp: weightOp,
      index: index
    })
  },
  submit() {
    let that = this;
    if (!that.data.height && !that.data.weight) return;
    let key = that.data.height ? "height" : "weight";

    wx.getStorage({
      key: 'student',
      success: function(res) {
        let studentId = res.data.studentId;
        let studentNumber = res.data.studentNumber;

        app.api.ajaxSubmit("/node/wx/mine/health/edit", {
          studentId: studentId,
          studentNumber: studentNumber,
          [key]: that.data[key]
        }).then(result => {
          if (result.data.error == 10000) {
            wx.showToast({
              title: '设置成功',
              duration: 2000,
              icon: "none"
            })
            that.updateInfo();
            that.cancel();
          }
        }).catch(err => {
          wx.showToast({
            title: '服务器开小差',
            duration: 2000,
            icon: "none"
          })
        })
      },
    })
  },
  updateInfo() {
    let that = this;
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2]; //上一个页面
    let key = that.data.height ? "height" : "weight";
    wx.setStorageSync(key, that.data[key]);
    prevPage.setData({
      [key]: that.data[key]
    })

  },
  cancel() {
    wx.navigateBack({
      delta: 1
    })
  }
})